# coding: utf-8
import cookielib
import urllib2

url = 'http://www.baidu.com'

# 直接使用
resp1 = urllib2.urlopen(url)
print resp1.getcode() # 获取状态码
print len(resp1.read())

# 使用Request
req = urllib2.Request(url)
req.add_header('user-agent', 'Mozilla/5.0')
resp2 = urllib2.urlopen(req)
print resp2.getcode()
print len(resp2.read())

# 使用cookie
cj = cookielib.CookieJar() # 创建cookie
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) # 添加cookie handler
urllib2.install_opener(opener) # 将handler注册入urllib2
resp3 = urllib2.urlopen(url)
print resp3.getcode()
print 'cookie : %s' % cj
print resp3.read()

